package com.example.attempt.utils;

import okhttp3.*;
import org.json.JSONObject;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

//Construct the vector of the paper
public class CalculateSimilar {
    public static double getSimilarResult1(String s1, String s2) throws IOException {
        long startTime = System.currentTimeMillis();
        String url="http://172.30.121.193:5000/predict";
        OkHttpClient client=new OkHttpClient();
        File f = new File(s1);
        File f1 = new File(s2);
        System.out.println("读取文件咯");
        String text = TextIO.readFile(s1);
        String text1 = TextIO.readFile(s2);
        System.out.println("文件查完咯");
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("sentence1", text);
        jsonBody.put("sentence2", text1);

        RequestBody requestBody = RequestBody.create(
                MediaType.parse("application/json"),
                jsonBody.toString()
        );
        // 构建请求
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        // 发送请求并获取响应
        Response response = client.newCall(request).execute();
        String json = response.body().string();
        JSONObject jsonObject = new JSONObject(json);
        double similarity = (double) jsonObject.get("similarity");

        return similarity;

    }
    public static double getSimilarResult(String s1, String s2) throws IOException {
        long startTime = System.currentTimeMillis();
        try{
            File f = new File(s1);
            File f1 = new File(s2);
            String text = TextIO.readFile(s1);
            String text1 = TextIO.readFile(s2);
            StringReader reader = new StringReader(text);
            StringReader reader1 = new StringReader(text1);
//            System.out.println("text:"+text);
//            System.out.println("text1:"+text1);

            if (f.length()!=0 && f1.length()!=0){
                if (f.length()<=30000){
                    double sim = 100 * CalculateSimilar.getSimilar(reader,reader1);
                    DecimalFormat df = new DecimalFormat();
                    String s = df.format(sim);
                    System.out.println(s+"%");
//                    TextIO.writeResultToFile(s1,s2,s3,s);
                    return sim;
                }else {
                    double sim = SimHash.Construct(reader,reader1);
                    System.out.println("The analysis result is "+sim*100+"%");
//                    TextIO.writeResultToFile(s1,s2,s3,String.valueOf(sim));
                    return sim;
                }
            }else {
                System.out.println("文件为空，请重新输入比较文本");
                return -1;
            }
        }catch (Exception e){
            System.out.println("文件路径有误，请重新输入");
        }
        long endTime = System.currentTimeMillis();
        System.out.println("The analysis time is " + (endTime-startTime) + "ms");
        return -1;
    }

    public static double getSimilar(Reader reader, Reader reader1) throws IOException {

        IKSegmenter ikSegmenter = new IKSegmenter(reader,true);
        IKSegmenter ikSegmenter1 = new IKSegmenter(reader1,true);

        Map<String, Integer> fre = getFrequency(ikSegmenter);
        Map<String, Integer> fre1 = getFrequency(ikSegmenter1);

        //利用words1将两个文本都合在一起，采用HashSet就是为了去重；
        Set<String> words1 = new HashSet<>();  //T(A, B)
        words1.addAll(fre.keySet());
        words1.addAll(fre1.keySet());

        Vector<Integer> FA = new Vector<>();
        Vector<Integer> FB = new Vector<>();

        //构造比较文本的特征向量
        for (String s : words1){
           if (fre.get(s)!=null){
               FA.add(fre.get(s));
           }else
               FA.add(0);
            if (fre1.get(s)!=null)
                FB.add(fre1.get(s));
            else
                FB.add(0);
        }
        //利用余弦进行相似度计算
        int sumA = 0;
        int sumB = 0;
        int sumAB = 0;
        for (int i=0;i<words1.size();i++){
            int a = FA.get(i);
            int b = FB.get(i);
            sumAB += a*b;
            sumA += a*a;
            sumB += b*b;
        }

        double  A = Math.sqrt(sumA);
        double  B = Math.sqrt(sumB);
        BigDecimal AB = BigDecimal.valueOf(A).multiply(BigDecimal.valueOf(B));
        return BigDecimal.valueOf(sumAB).divide(AB, 3, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    private static Map<String,Integer> getFrequency(IKSegmenter segmenter) throws IOException {
        Map<String, Integer> frequency = new HashMap<>();

        Lexeme word = segmenter.next();
        while(word!=null){
            String str = word.getLexemeText();
            if (frequency.get(str)==null){
                frequency.put(str,1);
            }else {
                int num = frequency.get(str);
                num++;
                frequency.put(str,num);
            }
            word = segmenter.next();
        }

        return frequency;
    }
}
